package com.jy.project.service.imp;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.project.domain.Dict;
import com.jy.project.domain.MaterialAttrField;
import com.jy.project.dto.*;
import com.jy.project.vo.*;
import com.jy.project.enums.DictTypeEnum;
import com.jy.project.enums.QualityStatusEnum;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.DictMapper;
import com.jy.project.mapper.MaterialAttrFieldMapper;
import com.jy.project.service.DictService;
import com.jy.project.service.MaterialAttrFieldService;
import com.jy.project.vo.DictVO;
import com.jy.project.vo.TreeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private MaterialAttrFieldService materialAttrFieldService;

    @Autowired
    private MaterialAttrFieldMapper materialAttrFieldMapper;

    @Override
    public boolean insertDept(DeptDTO dto) {
        dto.setDictType(DictTypeEnum.DEPT_TYPE.getCode());
        if (StringUtils.isEmpty(dto.getParentNo())) {
            dto.setParentNo("0");
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        if (dict == null) {
            throw new BizException("dic对象是空");
        }
        if (StringUtils.isEmpty(dict.getDictNo())) {
            throw new BizException("编号不能为空");
        }
        if (null == dict.getDictType()) {
            throw new BizException("类型不能为空");
        }
        if (StringUtils.isEmpty(dict.getName())) {
            throw new BizException("名称不能空");
        }
        DictVO dictVO = this.getDictVO(dict.getDictNo());
        if (dictVO != null) {
            throw new BizException("此编号已被使用");
        }
        if (!dict.getParentNo().equals("0")) {
            DictVO parentVO = this.getDictVO(dict.getParentNo());
            if (parentVO == null) {
                throw new BizException("上级分类已经被删除");
            }
        }
        Date date = new Date();
        dict.setUpdateDay(date);
        dict.setCreateAt(date);
        dict.setUpdateAt(date);
        dict.setIsDelete(0);
        dict.setStatus(0);
        return dictMapper.insertSelective(dict) > 0;
    }

    @Override
    @Transactional
    public boolean insertAssetClassDTO(AssetClassDTO dto) {
        dto.setDictType(DictTypeEnum.ASSET_CLASS.getCode());

        String parentNo = dto.getParentNo();
        String name = dto.getName();

        Dict dt = new Dict();
        dt.setParentNo(parentNo);
        dt.setName(name);
        dt.setDictType(DictTypeEnum.ASSET_CLASS.getCode());
        List<Dict> dicts = dictMapper.listParentDictByName(dt);
        if (!CollectionUtils.isEmpty(dicts)) {
            throw new BizException("已有该分类名称");
        }
        if (StringUtils.isEmpty(dto.getParentNo())) {
            dto.setParentNo("0");
        }

        //新增拓展属性
        List<MaterialAttrFieldDTO> attrs = dto.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {
            //封装拓展属性
            List<MaterialAttrField> materialAttrFieldList = attrs.stream().map(materialAttrFieldDTO -> {
                MaterialAttrField materialAttrField = new MaterialAttrField();
                return materialAttrField.setDictNo(dto.getDictNo()).setFieldName(materialAttrFieldDTO.getFieldName()).setFieldType(materialAttrFieldDTO.getFieldType()).setRequired(materialAttrFieldDTO.getRequired());
            }).collect(Collectors.toList());
            materialAttrFieldService.insertBatch(materialAttrFieldList);
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        //新增种类
        return insertDict(dict);
    }

    @Override
    public boolean insertRegion(RegionDTO dto) {
        String dictNo = dto.getDictNo();
        if (StringUtils.isEmpty(dictNo)) {
            throw new BizException("位置编号不能为空");
        }
        String name = dto.getName();
        if (StringUtils.isEmpty(name)) {
            throw new BizException("位置名称不能为空");
        }
        dto.setDictType(DictTypeEnum.REGION_TYPE.getCode());
        if (StringUtils.isEmpty(dto.getParentNo())) {
            dto.setParentNo("0");
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        return insertDict(dict);
    }

    @Override
    @Transactional
    public boolean deleteDictByNo(String dictNo) {
        if (StringUtils.isEmpty(dictNo)) {
            throw new BizException("编号不能为空");
        }
        String[] strings = dictNo.split(",");
        List<String> dictNos = Arrays.asList(strings);

        //删除拓展属性
        MaterialAttrField materialAttrField = new MaterialAttrField();
        materialAttrField.setIsDelete(1);
        Example attrExample = new Example(MaterialAttrField.class);
        attrExample.createCriteria().andIn("dictNo", dictNos);
        materialAttrFieldMapper.updateByExampleSelective(materialAttrField, attrExample);

        Dict dict = new Dict();
        dict.setDictNo(IdUtil.getSnowflake(1L, 1L).nextIdStr());
        dict.setIsDelete(1);
        Example example = new Example(Dict.class);
        example.createCriteria().andIn("dictNo", dictNos);
        return dictMapper.updateByExampleSelective(dict, example) > 0;
    }

    @Override
    public List<DictVO> listDeptDictVO(DictQueryDTO queryDTO) {
        String parentNo = queryDTO.getParentNo();
        if (StringUtils.isEmpty(parentNo)) {
            queryDTO.setParentNo("0");
        }
        queryDTO.setDictType(DictTypeEnum.DEPT_TYPE.getCode());
        return dictMapper.listDictVO(queryDTO);
    }

    @Override
    public List<TreeVO> listDeptDictTreeVO(DictQueryDTO queryDTO) {
        List<TreeVO> treeVOS = new ArrayList<>();
        List<DictVO> dictVOS = listDeptDictVO(queryDTO);
        if (CollectionUtils.isEmpty(dictVOS)) {
            return treeVOS;
        }
        return convert(dictVOS);
    }

    private List<TreeVO> convert(List<DictVO> dictVOS) {
        List<TreeVO> treeVOS = new ArrayList<>();
        for (int i = 0; i < dictVOS.size(); i++) {
            DictVO dictVO = dictVOS.get(i);
            TreeVO treeVO = new TreeVO();
            BeanUtils.copyProperties(dictVO, treeVO);
            DictQueryDTO dto = new DictQueryDTO();
            dto.setDictType(dictVO.getDictType());
            dto.setExt("2");
            dto.setParentNo(dictVO.getDictNo());
            List<DictVO> nodes = dictMapper.listDictVO(dto);
            List<TreeVO> nodeTreeVOS = new ArrayList<>();
            for (int i1 = 0; i1 < nodes.size(); i1++) {
                DictVO chNode = nodes.get(i1);
                TreeVO chNodeTreeVO = new TreeVO();
                BeanUtils.copyProperties(chNode, chNodeTreeVO);
                nodeTreeVOS.add(chNodeTreeVO);
                treeVO.setTreeExt(nodeTreeVOS);
            }
            treeVOS.add(treeVO);
        }
        return treeVOS;
    }

    @Override
    public List<DictVO> listRegionDictVO(DictQueryDTO queryDTO) {
        if (StringUtils.isEmpty(queryDTO.getExt())) {
            queryDTO.setExt("1");
        }
        queryDTO.setDictType(DictTypeEnum.REGION_TYPE.getCode());
        return dictMapper.listDictVO(queryDTO);
    }

    @Override
    public List<TreeVO> listRegionDictTreeVO(DictQueryDTO queryDTO) {
        List<TreeVO> treeVOS = new ArrayList<>();
        List<DictVO> dictVOS = listRegionDictVO(queryDTO);
        if (CollectionUtils.isEmpty(dictVOS)) {
            return treeVOS;
        }
        return convert(dictVOS);
    }

    @Override
    public List<DictVO> listAssetClassDictVO(DictQueryDTO queryDTO) {
        if (StringUtils.isEmpty(queryDTO.getExt())) {
            queryDTO.setExt("1");
        }
        queryDTO.setDictType(DictTypeEnum.ASSET_CLASS.getCode());
        return dictMapper.listDictVO(queryDTO);
    }

    @Override
    public List<TreeVO> listAssetClassDictTreeVO(DictQueryDTO queryDTO) {
        List<TreeVO> treeVOS = new ArrayList<>();
        List<DictVO> dictVOS = listAssetClassDictVO(queryDTO);
        if (CollectionUtils.isEmpty(dictVOS)) {
            return treeVOS;
        }
        return convert(dictVOS);
    }

    @Override
    public DictVO getDictVO(String dictNo) {
        Example example = new Example(Dict.class);
        example.createCriteria().andEqualTo("isDelete", 0).andEqualTo("dictNo", dictNo);
        Dict dict = dictMapper.selectOneByExample(example);
        if (dict == null) {
            return null;
        }
        DictVO dictVO = new DictVO();
        BeanUtils.copyProperties(dict, dictVO);
        return dictVO;
    }

    @Override
    public List<DictVO> listUnitDictVO(DictQueryDTO queryDTO) {
        queryDTO.setDictType(DictTypeEnum.UNIT.getCode());
        return dictMapper.listDictVO(queryDTO);
    }

    @Override
    public List<TreeVO> listUnitDictTreeVO(DictQueryDTO queryDTO) {
        List<TreeVO> treeVOS = new ArrayList<>();
        List<DictVO> dictVOS = listUnitDictVO(queryDTO);
        if (CollectionUtils.isEmpty(dictVOS)) {
            return treeVOS;
        }
        return convert(dictVOS);
    }

    @Override
    public boolean insertUnit(UnitDTO dto) {
        dto.setDictType(DictTypeEnum.UNIT.getCode());
        if (StringUtils.isEmpty(dto.getParentNo())) {
            dto.setParentNo("0");
        }
        if (StringUtils.isEmpty(dto.getDictNo())) {
            throw new BizException("分类编号不能为空");
        }
        if (StringUtils.isEmpty(dto.getName())) {
            throw new BizException("分类名称不能为空");
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        return insertDict(dict);
    }

    @Override
    public boolean update(DictUpdateDTO dto) {
        if (StringUtils.isEmpty(dto.getDictNo())) {
            throw new BizException("对应编号为空");
        }
        //拓展属性处理
        List<MaterialAttrFieldDTO> attrs = dto.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {
            List<MaterialAttrField> insertList = new ArrayList<>();
            for (MaterialAttrFieldDTO attr : attrs) {
                Long fieldId = attr.getFieldId();
                if (fieldId == null) {
                    MaterialAttrField materialAttrField = new MaterialAttrField();
                    materialAttrField.setDictNo(dto.getDictNo()).setFieldName(attr.getFieldName()).setFieldType(attr.getFieldType()).setRequired(attr.getRequired());
                    insertList.add(materialAttrField);
                } else {
                    //删除拓展属性
                    MaterialAttrField materialAttrField = new MaterialAttrField();
                    materialAttrField.setId(fieldId);
                    materialAttrField.setFieldName(attr.getFieldName());
                    materialAttrField.setFieldType(attr.getFieldType());
                    materialAttrField.setDictNo(dto.getDictNo());
                    materialAttrField.setRequired(attr.getRequired());
                    materialAttrField.setUpdateAt(new Date());
                    materialAttrFieldMapper.updateByPrimaryKeySelective(materialAttrField);
                }
            }


            materialAttrFieldService.insertBatch(insertList);
        }
        Example example = new Example(Dict.class);
        example.createCriteria().andEqualTo("dictNo", dto.getDictNo());
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        return dictMapper.updateByExampleSelective(dict, example) > 0;

    }

    @Override
    public boolean insertQuality(QualityDTO dto) {
        dto.setDictType(DictTypeEnum.QUALITY.getCode());
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        String qualityStatus = dto.getQualityStatus();
        if (StringUtils.isNotEmpty(qualityStatus)) {
            String[] qualityStatusArr = qualityStatus.split(",");
            dict.setExt(JSONObject.toJSONString(qualityStatusArr));
        }
        String dictNo = dict.getDictNo();
        if (StringUtils.isEmpty(dictNo)) {
            throw new BizException("编号不能为空");
        }
        int length = StringUtils.length(dictNo);

        if (length < 6) {
            throw new BizException("质量编号请输入6位");
        }
        if (null == dict.getDictType()) {
            throw new BizException("类型不能为空");
        }
        if (StringUtils.isEmpty(dict.getName())) {
            throw new BizException("名称不能空");
        }
        DictVO dictVO = this.getDictVO(dict.getDictNo());
        if (dictVO != null) {
            throw new BizException("此编号已经被占用");
        }
        dict.setParentNo("0");
        Date date = new Date();
        dict.setUpdateDay(date);
        dict.setCreateAt(date);
        dict.setUpdateAt(date);
        dict.setIsDelete(0);
        dict.setStatus(0);
        return dictMapper.insertSelective(dict) > 0;
    }

    @Override
    public List<QualityVO> listQualityVO(DictQueryDTO queryDTO) {
        List<QualityVO> list = new ArrayList<>();
        queryDTO.setDictType(DictTypeEnum.QUALITY.getCode());
        String no = "否";
        String yes = "是";
        List<DictVO> dictVOS = dictMapper.listDictVO(queryDTO);
        for (DictVO dictVO : dictVOS) {
            QualityVO qualityVO = new QualityVO();
            BeanUtils.copyProperties(dictVO, qualityVO);
            String ext = dictVO.getExt();
            if (StringUtils.isEmpty(ext)){
                ext="[1,2,3,4]";
            }
            String[] integers = JSON.parseObject(ext, String[].class);
            qualityVO.setCollect(no);
            qualityVO.setLoanable(no);
            qualityVO.setRefundable(no);
            qualityVO.setRegion(no);
            qualityVO.setQualityStatus(integers);
            for (String code : integers) {
                if (QualityStatusEnum.LOANABLE.getCode().toString().equals(code)) {
                    qualityVO.setLoanable(yes);
                }
                if (QualityStatusEnum.COLLECT_ABLE.getCode().toString().equals(code)) {
                    qualityVO.setCollect(yes);
                }
                if (QualityStatusEnum.REFUNDABLE.getCode().toString().equals(code)) {
                    qualityVO.setRefundable(yes);
                }
                if (QualityStatusEnum.REGION_TYPE.getCode().toString().equals(code)) {
                    qualityVO.setRegion(yes);
                }
            }
            list.add(qualityVO);
        }
        return list;
    }

    @Override
    public boolean updateQualityDTO(QualityDTO dto) {
        String dictNo = dto.getDictNo();
        DictVO dictVO = this.getDictVO(dictNo);
        Long id = dictVO.getId();
        if (dictVO == null) {
            throw new BizException("查询不到记录");
        }
        Integer dictType = dictVO.getDictType();
        if (!dictType.equals(DictTypeEnum.QUALITY.getCode())) {
            throw new BizException("类型不匹配");
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(dto, dict);
        String qualityStatus = dto.getQualityStatus();
        if (StringUtils.isNotEmpty(qualityStatus)) {
            String[] qualityStatusArr = qualityStatus.split(",");
            dict.setExt(JSONObject.toJSONString(qualityStatusArr));
        }
        dict.setId(id);
        dict.setUpdateAt(new Date());
        dict.setUpdateAt(new Date());
        return dictMapper.updateByPrimaryKeySelective(dict) > 0;

    }


    private boolean insertDict(Dict dict) {
        if (dict == null) {
            throw new BizException("dic对象是空");
        }
        if (StringUtils.isEmpty(dict.getDictNo())) {
            throw new BizException("编号不能为空");
        }
        if (null == dict.getDictType()) {
            throw new BizException("类型不能为空");
        }
        if (StringUtils.isEmpty(dict.getName())) {
            throw new BizException("名称不能空");
        }
        DictVO dictVO = this.getDictVO(dict.getDictNo());
        if (dictVO != null) {
            throw new BizException("此编号已被使用");
        }
        if (!dict.getParentNo().equals("0")) {
            DictVO parentVO = this.getDictVO(dict.getParentNo());
            if (parentVO == null) {
                throw new BizException("上级分类已经被删除");
            }
            dict.setExt("2");
        } else {
            dict.setExt("1");
        }
        Date date = new Date();
        dict.setUpdateDay(date);
        dict.setCreateAt(date);
        dict.setUpdateAt(date);
        dict.setIsDelete(0);
        dict.setStatus(0);
        return dictMapper.insertSelective(dict) > 0;
    }
}
